
exports.add=[{
	_type:"functions",
	_section:"Spreadsheets",

	/**
	 * Function: Spreadsheets.get_cell_pusher
	 */
	get_cell_pusher: function(ws) {
		var ws_id=ws.id;
		var t=this;
		return function(x,y,value) {
			t.site.sql.execute("cells/insert",{x:x,y:y,worksheet_id:ws_id,value:value});
		}
	},

	/**
	 * Function: Spreadsheets.get_table
	 */
	get_table: function(ws_id) {
		var table=[];
		var minmax=this.site.sql.execute_and_fetch_one_single("select min(x) as minx,max(x) as maxx,min(y) as miny,max(y) as maxy from Tcells where worksheet_id=:worksheet_id",{worksheet_id:ws_id});
		for (var y=0;y<minmax.maxy+1;y++) {
			var arr=[];
			for (var x=0;x<minmax.maxx+1;x++) arr.push("");
			table.push(arr);
		}
		this.site.sql.execute_and_fetch_single("select * from Tcells where worksheet_id=:worksheet_id",{worksheet_id:ws_id}).forEach(function(c) {
			table[c.y][c.x]=c.value;
		});
		return table;
	},

	/**
	 * Function: Spreadsheets.gen_html
	 */
	gen_html: function(table) {

	},

	/**
	 * Function: Spreadsheets.echo_xlsx
	 */
	echo_xlsx: function(fs, process, ss_id) {
		var ss = this.site.models.Spreadsheet.Get(ss_id);
		if (!ss) throw "Bad spreadsheet_id = " + ss_id;

		var fname = ss.name.replace(/[\s'"\/]+/g, '_');
		if (!fname.match(/.xlsx$/)) {
			fname += '.xlsx';
		}

		var fpath = '/tmp/' + ss.id + '-' + fname

		var f = new fs.File(fpath);
		if (f.exists()) f.remove();

		var p=new process.Process();
		// warning! you must escape args!
		p.system([
			'/home/projects/lattenoir/files/xls_export.pl',
			this.site.database.login,
			this.site.database.password,
			this.site.database.database,
			ss.id,
			fpath,
		].join(' '));

		f.open("r");
		var ret = f.read();
		f.close();

		this.jsng_response.response_headers["Content-type"]="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
		this.jsng_response.response_headers["Content-disposition"]="attachment; filename='"+fname+"'";

		return ret;
	},
}];

